package com.wh.order.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.wh.basic.utils.TimeUtil;
import com.wh.basic.vo.AjaxResult;
import com.wh.custom.dao.CustomMycustomMapper;
import com.wh.custom.mapper.CustomReturnVisitMapper;
import com.wh.custom.pojo.CustomMycustom;
import com.wh.custom.pojo.CustomReturnVisit;
import com.wh.order.dao.OrderListMapper;
import com.wh.order.dto.*;
import com.wh.order.mapper.OrderDetailMapper;
import com.wh.order.mapper.OrderProducidMapper;
import com.wh.order.mapper.OrderReviewerMapper;
import com.wh.order.pojo.OrderDetail;
import com.wh.order.pojo.OrderList;
import com.wh.order.pojo.OrderProducid;
import com.wh.order.pojo.OrderReviewer;
import com.wh.order.service.IOrderListService;
import com.wh.order.util.OrderExport;
import com.wh.order.util.orderImportExcelVerify;
import com.wh.order.vo.OrderExportVo;
import com.wh.order.vo.OrderProductVo;

import com.wh.org.dao.IEmployeeDao;
import com.wh.sse.controller.SseController;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 业务实现类
 */
@Service
public class OrderListServiceImpl extends ServiceImpl<OrderListMapper, OrderList> implements IOrderListService {

    @Autowired
    private OrderListMapper orderListMapper;
    @Autowired
    private IEmployeeDao iEmployeeDao;
    @Autowired
    private OrderDetailServiceImpl orderDetailService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private CustomMycustomMapper customMycustomMapper;

    @Autowired
    private OrderProducidMapper orderProducidMapper;

    @Autowired
    private IEmployeeDao employeeDao;
    @Autowired
    private OrderReviewerMapper orderReviewerMapper;
    @Autowired
    private orderImportExcelVerify orderVerify;
    @Autowired
    private CustomReturnVisitMapper customReturnVisitMapper;
    @Autowired
    private SseController sseController;


    @Override
    public IPage<OrderList> findByPage(PageDto pageDto) {
        Integer orderState = pageDto.getRuleSelectForm().getOrderState();
        String trackingNumbe = pageDto.getRuleSelectForm().getTrackingNumber();
        SelectRuleDto ruleSelectForm = pageDto.getRuleSelectForm();
        String startTime = ruleSelectForm.getStartTime();
        String endTime = ruleSelectForm.getEndTime();
        //1.创建查询条件
        QueryWrapper<OrderList> qw = new QueryWrapper<>();
        if (orderState != null) {
            qw.eq("order_state", orderState);
        }
        if (!trackingNumbe.isEmpty()) {
            qw.eq("tracking_number", trackingNumbe);
        }
        if (startTime != null && !startTime.isEmpty() && endTime != null && !endTime.isEmpty()) {
            qw.between("create_time", startTime, endTime);
        }
        IPage<OrderList> page = new Page<>(pageDto.getCurrentPage(), pageDto.getPageSize());
        page.setRecords(orderListMapper.findByPage(page, qw));

        page.setTotal(orderListMapper.selectCount(qw));

        return page;
    }

    /**
     * 创建订单
     *
     * @param orderList
     */
    @Transactional
    @Override
    @Async
    public void saveOrder(OrderList orderList) {
        String orderSn = orderList.getOrderSn();//订单编号
        Integer orderReviewerId = orderList.getOrderReviewerId();//订单审核人
        //1收货人信息添加
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setName(orderList.getOrderDetail().getName());
        orderDetail.setPhone(orderList.getOrderDetail().getPhone());
        orderDetail.setProvince(orderList.getOrderDetail().getProvince());
        orderDetail.setCity(orderList.getOrderDetail().getCity());
        orderDetail.setDistrict(orderList.getOrderDetail().getDistrict());
        orderDetail.setDetailAddress(orderList.getOrderDetail().getDetailAddress());
        orderDetailService.save(orderDetail);
        Integer id = orderDetail.getId();
        //2通过订单编号和产品id保存订单里的多个产品，遍历List集合
        OrderProducid orderProd = new OrderProducid();
        List<OrderProducid> orderProducids = orderList.getOrderProducids();
        BigDecimal totalAmount = BigDecimal.ZERO;//订单金额初始化为0
        Long orderNumTotal=0L;
        for (OrderProducid orderProducid : orderProducids) {
            BigDecimal orderAmount = orderProducid.getOrderAmount();
            Integer orderNum=orderProducid.getOrderNum();
            orderProd.setOrderSn(orderSn);
            orderProd.setProductId(orderProducid.getProductId());
            orderProd.setOrderNum(orderProducid.getOrderNum());
            orderProd.setOrderAmount(orderAmount);
            orderProd.setSalePrice(orderProducid.getSalePrice());
            orderProducidMapper.insert(orderProd);
            totalAmount = totalAmount.add(orderAmount);
            //计算订单总下单数量
            orderNumTotal = orderNumTotal+orderNum;
        }
        orderList.setOrderAmount(totalAmount);//订单总金额
        orderList.setProductNumber(orderNumTotal);//订单总下单数量
        //2.1 获取此订单的客户id,获取此客户的历史总下单金额，数量 为客户列表的总金额赋值
        CustomMycustom customMycustom = customMycustomMapper.selectById(orderList.getCustomerId());
        customMycustom.setTotalAmount(customMycustom.getTotalAmount().add(totalAmount));
        customMycustom.setOrderProductCount(customMycustom.getOrderProductCount()+orderNumTotal);
        customMycustom.setTotalDealCount(customMycustom.getTotalDealCount()+1);
        customMycustom.setUpdateTime(LocalDateTime.now());
        customMycustomMapper.updateById(customMycustom);
        //获取客户的归属人
        Integer customerId = orderList.getCustomerId();    //获取订单客户的归属人
        Long salesmanId= customMycustomMapper.selectSaleamnId(customerId);

        Long loginId = orderList.getLoginId();
        Long personId = iEmployeeDao.findEmployeeIdByloginId(loginId);//获取当前登录人，用于活跃记录记录操作人信息

        //订单创建时间
        orderList.setCreateTime(LocalDateTime.now());
        //采用枚举来定义订单状态
        orderList.setOrderState(OrderStatus.WAITING_FOR_REVIEW.getCode());
        //设置订单归属人为客户归属人
        orderList.setPersonId(salesmanId);
        orderList.setOrderDetailId(id);
        //3.订单审核人处理
        OrderReviewer orderReviewer = new OrderReviewer();
        orderReviewer.setOrderSn(orderSn).setJuniorReviewer(orderReviewerId);
        orderReviewerMapper.insert(orderReviewer);
        orderListMapper.insertOrder(orderList);
        //4增加回访表的记录，为此客户创建了一次订单
        CustomReturnVisit customReturnVisit = new CustomReturnVisit();

        customReturnVisit.setOrderSn(orderSn);
        customReturnVisit.setCustomId(new Long(customerId));
        customReturnVisit.setDate(LocalDateTime.now());
        customReturnVisit.setRecordType(1);
        customReturnVisit.setOperator(personId);
        customReturnVisit.setContent("创建订单，订单编号："+orderList.getOrderSn());
        customReturnVisitMapper.insert(customReturnVisit);
        //发送消息给订单待审核人;
        //获取订单审核人的登录id
        Long logininfoIdByid = iEmployeeDao.findLogininfoIdByid(new Long(orderReviewerId));
        String newOrderMessage="您有一条订单编号为: "+orderSn+" 的订单刚创建完成,需要您去审核,请到审核管理页面查看! ";
        sseController.sendAppointMessage(logininfoIdByid,newOrderMessage);
    }

    /**
     * 通过客户id查询客户订单
     *
     * @param customerOrderDto
     * @return
     */
    @Override
    public IPage<OrderList> getCustomerOrders(CustomerOrderDto customerOrderDto) {
        //1获取客户id
        Integer customerId = customerOrderDto.getOrdercustomerId();
        //2通过客户id获取客户订单 筛选

        QueryWrapper<OrderList> qw = new QueryWrapper<>();
        IPage<OrderList> page = new Page<>(customerOrderDto.getCurrentPage(), customerOrderDto.getPageSize());
        qw.eq("customer_id", customerId);
        qw.ne("order_state", OrderStatus.WAITING_FOR_REVIEW.getCode());   //不查询待审核订单
        qw.ne("order_state", OrderStatus.WAITING_FOR_RECHECK.getCode());//不查询待复核的订单
        qw.ne("order_state", OrderStatus.REVIEW_FAILED.getCode());//不查询审核未通过的订单

        //2查询数据列表之后返回
        page.setRecords(orderListMapper.findByPage(page, qw));
        page.setTotal(orderListMapper.selectCount(qw));
        return page;

    }

    /**
     * 查询当前归属人的 订单
     *
     * @param pageDto
     * @return
     */
    @Override
    public IPage<OrderList> findByPageMyOrder(PageDto pageDto) {
        Integer orderState = pageDto.getRuleSelectForm().getOrderState();
        String trackingNumbe = pageDto.getRuleSelectForm().getTrackingNumber();

        SelectRuleDto ruleSelectForm = pageDto.getRuleSelectForm();
        String startTime = ruleSelectForm.getStartTime();
        String endTime = ruleSelectForm.getEndTime();
        Long logininfo = pageDto.getLogininfo();
        //当前登陆人的id
        Long logininfoId = employeeDao.findEmployeeIdByloginId(logininfo);
        QueryWrapper<OrderList> qw = new QueryWrapper<>();
        qw.like("person_id", logininfoId);
        if (orderState != null) {
            qw.eq("order_state", orderState);
        }
        if (!trackingNumbe.isEmpty()) {
            qw.eq("tracking_number", trackingNumbe);
        }
        if (startTime != null && !startTime.isEmpty() && endTime != null && !endTime.isEmpty()) {
            qw.between("create_time", startTime, endTime);
        }

        IPage<OrderList> page = new Page<>(pageDto.getCurrentPage(), pageDto.getPageSize());
        page.setRecords(orderListMapper.findMyOrderByPage(page, qw));
        page.setTotal(orderListMapper.selectCount(qw));
        return page;
    }

    @Override
    public OrderList findOne(String orderSn) {

        return orderListMapper.findOne(orderSn);
    }

    /**
     * 获取订单总金额（统计订单交易完成的）
     *
     * @param type
     * @return
     */
    @Override
    public Map<String, Object> getTotalAmount(String type) {
        Map<String, Object> map = new HashMap<>();
        Double amount;
        Double lastAmount;
        if ("year".equals(type)) {
            //年度统计
            amount = orderListMapper.getNowYearTotalAmount();
            lastAmount = orderListMapper.getLastYearTotalAmount();
            if (amount > lastAmount) {
                map.put("isProfit", true);
            } else {
                map.put("isProfit", false);
            }
            if (amount.equals(lastAmount)) {
                map.put("isConsistent", true);
            } else {
                map.put("isConsistent", false);
            }
            map.put("totalAmount", amount);
            map.put("lastAmount", lastAmount);
        } else if ("month".equals(type)) {
            //月度统计
            amount = orderListMapper.getNowMonthTotalAmount();
            lastAmount = orderListMapper.getLastMonthTotalAmount();
            if (amount > lastAmount) {
                map.put("isProfit", true);
            } else {
                map.put("isProfit", false);
            }
            if (amount.equals(lastAmount)) {
                map.put("isConsistent", true);
            } else {
                map.put("isConsistent", false);
            }
            map.put("totalAmount", amount);
            map.put("lastAmount", lastAmount);
        } else if ("week".equals(type)) {
            //周度统计
            amount = orderListMapper.getNowWeekTotalAmount();
            lastAmount = orderListMapper.getLastWeekTotalAmount();
            if (amount > lastAmount) {
                map.put("isProfit", true);
            } else {
                map.put("isProfit", false);
            }
            if (amount.equals(lastAmount)) {
                map.put("isConsistent", true);
            } else {
                map.put("isConsistent", false);
            }
            map.put("totalAmount", amount);
            map.put("lastAmount", lastAmount);
        }
        return map;
    }

    @Override
    public List<OrderProductVo> getHotProductCount(String type) {
        if ("year".equals(type)) {
            return orderListMapper.getNowYearHotProduct();
        } else if ("month".equals(type)) {
            return orderListMapper.getNowMonthHotProduct();
        } else if ("week".equals(type)) {
            return orderListMapper.getNowWeekHotProduct();
        }
        return null;
    }

    @Override
    public OrderExport export(List<OrderExportDto> exportDtos, String[] orderSn) {
        if (!ObjectUtils.isEmpty(exportDtos)) {
            String[] props = new String[exportDtos.size() + 1];
            String[] labels = new String[exportDtos.size() + 1];
            for (int i = 0; i < exportDtos.size(); i++) {
                OrderExportDto orderExportDto = exportDtos.get(i);
                if (orderExportDto.getChecked()) {
                    props[i] = orderExportDto.getProp();
                    labels[i] = orderExportDto.getLabel();
                }
            }
            //根据订单编号查询出所有订单数据
            List<OrderExportVo> exportVos = orderListMapper.findAllExportOrder(orderSn);
            OrderExport orderExport = new OrderExport();
            orderExport.setLabels(labels);
            orderExport.setProps(props);
            orderExport.setExportVos(exportVos);
            return orderExport;
        }
        return null;
    }


    /**
     * 订单导出（采用esaypoi）
     *
     * @param response
     * @param orderSn
     */
    public void exportOrders(HttpServletResponse response, @RequestBody List<String> orderSn) {
        // 获取订单列表
        List<OrderExportVo> orders = orderListMapper.getOrdersBySnsAndColumns(orderSn);
        // 获取订单产品信息
        List<OrderProducid> orderProducids = orderListMapper.selectProduct(orderSn);
        // 创建一个Map集合，以订单编号为key值,以List<OrderProducid>为值，存放多个产品信息
        Map<String, List<OrderProducid>> productMap = orderProducids.stream()
                .collect(Collectors.groupingBy(OrderProducid::getOrderSn));
        // 遍历订单列表，将产品信息添加到对应的订单对象中，并计算每个订单的总金额
        for (OrderExportVo order : orders) {
            // 添加产品信息
            String orderSn1 = order.getOrderSn();
            List<OrderProducid> productExportVoList = productMap.get(orderSn1);
            if (productExportVoList != null) {
                order.setOrderProducids(productExportVoList);
            }
        }

        // 去重处理，确保订单列表中没有重复的订单和产品信息（根据订单编号和产品名称）
        Map<String, OrderExportVo> uniqueOrdersMap = new LinkedHashMap<>();
        for (OrderExportVo order : orders) {
            String orderSn1 = order.getOrderSn();
            List<OrderProducid> uniqueProducts = order.getOrderProducids().stream()
                    .collect(Collectors.toMap(OrderProducid::getProductName, p -> p, (p1, p2) -> p1))
                    .values().stream().collect(Collectors.toList());
            order.setOrderProducids(uniqueProducts);
            uniqueOrdersMap.put(orderSn1, order);
        }
        List<OrderExportVo> uniqueOrders = new ArrayList<>(uniqueOrdersMap.values());

        // 统计所有订单的总金额
        double totalAmount = uniqueOrders.stream()
                .mapToDouble(OrderExportVo::getOrderAmount)
                .sum();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd");
        String time = dateFormat.format(new Date());

        ExportParams exportParams = new ExportParams("订单信息表", "订单信息", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, OrderExportVo.class, uniqueOrders);

        // 在工作表的末尾添加总计行
        Sheet sheet = workbook.getSheet(exportParams.getSheetName());
        int lastRowNum = sheet.getLastRowNum() + 1; // 获取最后一行的行号，并加1以在最后一行之后插入新行
        Row summaryRow = sheet.createRow(lastRowNum);
        summaryRow.createCell(0).setCellValue("导出的订单总金额是:");
        summaryRow.createCell(1).setCellValue(totalAmount);

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + "订单信息表" + time + ".xls");
        try {
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 修改订单
     *
     * @param orderList
     */
    @Transactional
    @Override
    public void editOrder(OrderList orderList) {
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setId(orderList.getOrderDetail().getId());
        orderDetail.setName(orderList.getOrderDetail().getName());
        orderDetail.setPhone(orderList.getOrderDetail().getPhone());
        orderDetail.setProvince(orderList.getOrderDetail().getProvince());
        orderDetail.setCity(orderList.getOrderDetail().getCity());
        orderDetail.setDistrict(orderList.getOrderDetail().getDistrict());
        orderDetail.setDetailAddress(orderList.getOrderDetail().getDetailAddress());
        orderDetailMapper.updateById(orderDetail);
        String orderSn = orderList.getOrderSn();
        //订单相关的修改只修改了支付方式,支付状态,订单备注,以及最近操作时间
        String notes = orderList.getNotes();
        String payType = orderList.getPayType();//支付方式
        Integer paymentStatus = orderList.getPaymentStatus();//支付状态
        //设置最后操作时间为当前时间
        LocalDateTime lastOperaTime = LocalDateTime.now();
        orderListMapper.editOrder(orderSn, payType, paymentStatus, lastOperaTime,notes);
    }


    @Transactional
    @Override
/**
 * 发货
 * @param orderList
 */
    public void sendoutgoods(OrderList orderList) {
        String logisticsCompanies = orderList.getLogisticsCompanies();//获取物流公司
        String logisticsMethods = orderList.getLogisticsMethods();//物流方式
        String trackingNumber = orderList.getTrackingNumber();//快递单号
        String Remarks = orderList.getRemarks();//物流备注
        String voucher = orderList.getVoucher();//发货凭证
        String orderSn = orderList.getOrderSn();//订单号
        String payType = orderList.getPayType();//支付方式
        String receipt = orderList.getReceipt();//支付凭证
//        List<OrderProductDto> orderProductDtos = orderProducidMapper.findproductIdByordersn(orderSn);

        Integer orderState = OrderStatus.SHIPPED.getCode();//状态改为已发货
        LocalDateTime deliveryTime = LocalDateTime.now();//发货时间

        orderListMapper.sendoutgoods(receipt, payType, orderSn, logisticsCompanies, logisticsMethods, trackingNumber, Remarks, voucher, orderState, deliveryTime);
//        //库存处理
//        /**
//         * 发货成功，库存减少
//         */
//        //根据产品id查询库存id
//        for (OrderProductDto orderProductDto : orderProductDtos) {
//            Integer productId = orderProductDto.getProductId();
//            Long orderNum = orderProductDto.getOrderNum();
//            Long StockId = productListMapper.findstockIdByprooductId(productId);
//            //发货成功，库存减少
//            stockMapper.stockprocessing(orderNum, StockId);
//        }
    }

    /**
     * 订单取消
     *
     * @param orderList
     */
    @Transactional
    @Override
    public void cancel(OrderList orderList) {
        Integer orderState = OrderStatus.ORDER_CANCELLED.getCode();//订单状态为取消
        String orderSn = orderList.getOrderSn();//订单号
        String reasonForCancellation = orderList.getReasonForCancellation();//取消原因
//        List<OrderProductDto> orderProductDtos = orderProducidMapper.findproductIdByordersn(orderSn);
        orderListMapper.cancel(orderSn, reasonForCancellation, orderState);
        //根据产品id查询库存id
//        for (OrderProductDto orderProductDto : orderProductDtos) {
//            Integer productId = orderProductDto.getProductId();
//            Long orderNum = orderProductDto.getOrderNum();
//            Long StockId = productListMapper.findstockIdByprooductId(productId);
//            //订单取消库存回增
//            stockMapper.stockprocessingAdd(orderNum,StockId);
//        }

    }

    /**
     * 订单审核
     *
     * @param orderReviewer
     */
    @Transactional
    @Override
    @Async
    public void Examine(OrderReviewer orderReviewer) {
        String orderSn = orderReviewer.getOrderSn();
        Integer findingOfAudit = orderReviewer.getFindingOfAudit();
        //审核结果是拒绝
        //1通过 2拒绝
        if (findingOfAudit == 2) {
            //审核未通过状态码
            Integer failedCode = OrderStatus.REVIEW_FAILED.getCode();
            //订单直接为审核未通过
            orderListMapper.Fail(orderSn, findingOfAudit, failedCode);
        }
        //审核通过
        if (findingOfAudit == 1) {
            Integer orderState = orderReviewer.getOrderState();//订单状态，用于判断是待审核，待复审，待终审
            LocalDateTime examineTime = LocalDateTime.now();
            //进行初审
            if (orderState == 0) {
                Integer code = OrderStatus.WAITING_FOR_RECHECK.getCode();//订单状态改为待复审
                Integer reviewer = orderReviewer.getIntermediateReviewer();//下级审核人
                orderListMapper.FirstTrial(orderSn, code, reviewer);

                String juniorReviewerNotes = orderReviewer.getJuniorReviewerNotes();//审核理由
                orderReviewerMapper.firstExamine(examineTime, orderSn, reviewer, juniorReviewerNotes);
           //发送消息给待复审人;
                Long reviewerlogId = iEmployeeDao.findLogininfoIdByid(new Long(reviewer));
                //发送审核消息
                String reviewerMessage="您有一条新的订单编号为:"+orderSn+" 的待复审订单,请到审核管理页面查看!";
                sseController.sendAppointMessage(reviewerlogId,reviewerMessage);
            }
            //进行复审
            if (orderState == 1) {
                Integer code = OrderStatus.WAITING_FOR_FINALREVIEWER.getCode();//待终审
                Integer reviewer = orderReviewer.getFinalReviewer();//下级审核人
                orderListMapper.FirstTrial(orderSn, code, reviewer);

                String IntermediateReviewerNotes = orderReviewer.getIntermediateReviewerNotes();//审核理由
                orderReviewerMapper.secondExamine(reviewer, examineTime, IntermediateReviewerNotes, orderSn);
                //发送消息给待终审人;
                Long reviewerlogId = iEmployeeDao.findLogininfoIdByid(new Long(reviewer));
                //发送审核消息
                String reviewerMessage="您有一条新的订单编号为:"+orderSn+" 的待终审订单,请到审核管理页面查看!";
                sseController.sendAppointMessage(reviewerlogId,reviewerMessage);
            }
            //进行待终审
            if (orderState == 7) {
                Integer code = OrderStatus.WAITING_FOR_SHIPMENT.getCode();//审核通过，订单改为待发货
                orderListMapper.finaexamine(orderSn, code);
                String finalReviewerNotes = orderReviewer.getFinalReviewerNotes();
                orderReviewerMapper.finalExamine(orderSn, finalReviewerNotes, examineTime);
                //获取订单归属人
               Long personId= orderListMapper.findpersonId(orderSn);
                //发送消息给待复审人;
                Long reviewerlogId = iEmployeeDao.findLogininfoIdByid(new Long(personId));
                //发送审核消息
                String reviewerMessage="您创建的订单:"+orderSn+" 审核已通过,请到我的订单页面进行后续操作";
                sseController.sendAppointMessage(reviewerlogId,reviewerMessage);
            }
        }

    }


    /**
     * 查询自己账号的审核订单
     *
     * @return
     */
    @Override
    public IPage<OrderList> getAuditOrders(AuditOrdersDto auditOrdersDto) {
        QueryWrapper<OrderList> qw = new QueryWrapper<>();
        //1获取当前登录人的id，根据id去查订单表的归属人id，
        Long auditLoginId = iEmployeeDao.findEmployeeIdByloginId(auditOrdersDto.getLoginId());
        Integer[] allowedOrderStates = {0, 1, 7};  // 订单状态为 0 或 1
        IPage<OrderList> page = new Page<>(auditOrdersDto.getCurrentPage(), auditOrdersDto.getPageSize());
        qw.eq("order_reviewer_id", auditLoginId);
        qw.in("order_state", allowedOrderStates);
        //2查询数据列表之后返回
        page.setRecords(orderListMapper.findByPage(page, qw));
        page.setTotal(orderListMapper.selectCount(qw));
        return page;
    }

    /* */

    /**
     * 审核后 修改订单状态
     * 一级审核
     *//*
    @Override
    public void updateState(Long id) {
        //1查出要修改的订单
        OrderList orderList = orderListMapper.selectById(id);
        //2获取订单状态，然后修改
        orderList.setOrderState(2);
    }*/

    /**
     * 获取 年/月/周 订单数量进行统计汇总
     *
     * @param type
     * @return
     */
    @Override
    public Map<String, Object> getOrderDataCount(String type) {
        Map<String, Object> maps = new HashMap<>();
        if ("year".equals(type)) {
            List<Integer> counts = new ArrayList<>();
            LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
            List<String> nowYearMonth = TimeUtil.getNowYearMonth();
            maps.put("subscript", nowYearMonth);
            for (String yearMonth : nowYearMonth) {
                map.put(yearMonth, 0);
            }
            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy");
            String year = currentDate.format(formatter);
            List<OrderList> orderLists = orderListMapper.getOrderDataByNowYear(year);
            if (!ObjectUtils.isEmpty(orderLists)) {
                DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyy-MM");
                for (OrderList orderList : orderLists) {
                    LocalDateTime createTime = orderList.getCreateTime();
                    String date = createTime.format(ofPattern);
                    if (map.containsKey(date)) {
                        Integer count = map.get(date);
                        map.put(date, count + 1);
                    }
                }
            }
            for (String key : map.keySet()) {
                Integer value = map.get(key);
                counts.add(value);
            }
            maps.put("count", counts);
        } else if ("month".equals(type)) {
            List<Integer> counts = new ArrayList<>();
            List<String> nowMonthDay = TimeUtil.getNowMonthDay();
            maps.put("subscript", nowMonthDay);
            LinkedHashMap<String, Integer> map = new LinkedHashMap<>();

            for (String monthDay : nowMonthDay) {
                map.put(monthDay, 0);
            }
            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
            String currentYearMonth = currentDate.format(formatter);
            List<OrderList> orderLists = orderListMapper.getOrderDataByNowMonth(currentYearMonth);
            if (!ObjectUtils.isEmpty(orderLists)) {
                DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                for (OrderList orderList : orderLists) {
                    LocalDateTime createTime = orderList.getCreateTime();
                    String date = createTime.format(ofPattern);
                    if (map.containsKey(date)) {
                        Integer count = map.get(date);
                        map.put(date, count + 1);
                    }
                }
            }
            for (String key : map.keySet()) {
                Integer value = map.get(key);
                counts.add(value);
            }
            maps.put("count", counts);
        } else if ("week".equals(type)) {
            List<Integer> counts = new ArrayList<>();
            List<String> nowWeekDay = TimeUtil.getNowWeekDay();
            maps.put("subscript", nowWeekDay);
            LinkedHashMap<String, Integer> map = new LinkedHashMap<>();

            for (String weekDay : nowWeekDay) {
                map.put(weekDay, 0);
            }
            List<OrderList> orderLists = orderListMapper.getOrderDataByNowWeek();
            if (!ObjectUtils.isEmpty(orderLists)) {
                DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                for (OrderList orderList : orderLists) {
                    LocalDateTime createTime = orderList.getCreateTime();
                    String date = createTime.format(ofPattern);
                    if (map.containsKey(date)) {
                        Integer count = map.get(date);
                        map.put(date, count + 1);
                    }
                }
            }
            for (String key : map.keySet()) {
                Integer value = map.get(key);
                counts.add(value);
            }
            maps.put("count", counts);
        }
        return maps;
    }

    @Override
    public Integer allNum() {
        return orderListMapper.selectCount(null);
    }

    @Override
    public Map<String, Long> getTime() {
        HashMap<String, Long> timeMap = new HashMap<>();
        // 获取全部订单数据
        List<OrderList> orderLists = orderListMapper.selectList(null);

        // 获取时间存到list集合
        List<LocalDateTime> dateTimes = new ArrayList<>();
        for (OrderList orderList : orderLists) {
            LocalDateTime createTime = orderList.getCreateTime();
            dateTimes.add(createTime);
        }

        // 遍历集合中时间，每天时间作为一个 key，同一天的订单数量算出来作为 value
        for (LocalDateTime dateTime : dateTimes) {
            // 将 LocalDateTime 格式化为年月日字符串
            String formattedDate = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

            // 计算同一天的订单数量
            long orderCount = dateTimes.stream()
                    .filter(dt -> dt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).equals(formattedDate))
                    .count();

            // 将结果放入 Map
            timeMap.put(formattedDate, orderCount);
        }

        return timeMap;
    }

    @Override
    @Async
    @Transactional
    public AjaxResult importOrder( MultipartFile file) {
        ImportParams importParams = new ImportParams();
        importParams.setHeadRows(1); // 表头
        importParams.setTitleRows(1); // 标题
        importParams.setStartSheetIndex(0); // 设置开始导入的sheet页，默认为0
        importParams.setStartRows(1);
        // 自定义效验
        importParams.setVerifyHandler(orderVerify);
        try {

            ExcelImportResult<OrderExportVo> result = ExcelImportUtil.importExcelMore(file.getInputStream(), OrderExportVo.class, importParams);
            // 导入成功的数据
            List<OrderExportVo> list = result.getList();

            for (OrderExportVo orderExportVo : list) {
                //根据订单编号存放对应的物流单号
                String orderSn = orderExportVo.getOrderSn();
                String orderStatus = orderExportVo.getOrderStatus();
                // 如果是统计数据，直接跳过
                if ("导出的订单总金额是:".equals(orderSn)) {
                    continue;
                }
                //如果不是待发货的，跳过
                if(!orderStatus.equals("待发货")){
                    continue;
                }
                orderListMapper.importOrder(orderSn,orderExportVo.getTrackingNumber());
            }

            // 失败结果集
            boolean verifyFail = result.isVerifyFail();
            if (verifyFail) {
                List<OrderExportVo> errorList = result.getFailList();
                List<Map<String, String>> errorDetails = new ArrayList<>();
                for (OrderExportVo error : errorList) {
                    Map<String, String> errorDetail = new HashMap<>();
                    errorDetail.put("orderSn", error.getOrderSn());
                    errorDetail.put("errorMessage", error.getErrorMsg());
                    errorDetails.add(errorDetail);
                }
                // 返回错误信息
                return AjaxResult.me().setSuccess(false).setMessage("文件导入失败").setResultObj(errorDetails);
            } else {
                // 如果没有错误，返回成功信息
                return AjaxResult.me().setSuccess(true).setMessage("文件导入成功");
            }
        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常情况
            return AjaxResult.me().setSuccess(false).setMessage("文件读取错误：" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            // 处理其他异常情况
            return AjaxResult.me().setSuccess(false).setMessage("导入过程错误：" + e.getMessage());
        }
    }

    /**
     * 导出异步线程处理，提高并发任务
     *
     * @param response
     * @param orderSn
     */
    @Async
    @Override
    public void exportOrdersAsync(HttpServletResponse response, List<String> orderSn) {
        exportOrders(response, orderSn);
    }

    /**
     * 客服下单列表
     * @param pageDto
     * @return
     */
    @Override
    public IPage<OrderList> customerServiceFindByPage(PageDto pageDto) {
        Integer orderState = pageDto.getRuleSelectForm().getOrderState();

        String trackingNumbe = pageDto.getRuleSelectForm().getTrackingNumber();
        SelectRuleDto ruleSelectForm = pageDto.getRuleSelectForm();
        String startTime = ruleSelectForm.getStartTime();
        String endTime = ruleSelectForm.getEndTime();
        //1.创建查询条件
        QueryWrapper<OrderList> qw = new QueryWrapper<>();
        qw.ne("order_state", 0);   //不查询待审核订单
        qw.ne("order_state", 1);   //不查询待复审订单
        qw.ne("order_state", 2);//不查询审核未通过的订单
        qw.ne("order_state", 7);//不查询审核待终审的订单
        qw.eq("logistics_methods","快递");
        if (orderState != null) {
            qw.eq("order_state", orderState);
        }
        if (!trackingNumbe.isEmpty()) {
            qw.eq("tracking_number", trackingNumbe);
        }
        if (startTime != null && !startTime.isEmpty() && endTime != null && !endTime.isEmpty()) {
            qw.between("create_time", startTime, endTime);
        }

        IPage<OrderList> page = new Page<>(pageDto.getCurrentPage(), pageDto.getPageSize());
        page.setRecords(orderListMapper.customerServiceFindByPage(page, qw));

        page.setTotal(orderListMapper.selectCount(qw));

        return page;
    }

    @Override
    public void takeDelivery(String orderSn) {
        //收货时间
        LocalDateTime successTime = LocalDateTime.now();
        //收货状态
        Integer orderstate=5;
        orderListMapper.takeDelivery(successTime,orderstate,orderSn);
    }
}
